package com.example.pets.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pets.R;
import com.example.pets.model.entities.Post;
import com.example.pets.model.entities.database.AppDatabase;
import com.example.pets.view.activity.PostActivity;
import com.example.pets.view.fragment.adapter.PostAdapter;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    public HomeFragment() {}
    private ArrayList<Post> postDataList;

    private RecyclerView rvPostList;
    private PostAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        // 设置Toolbar和发布按钮
        Button btnAddPost = view.findViewById(R.id.btn_add_post);
        btnAddPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PostActivity.class);
                startActivity(intent);
            }
        });

        rvPostList =view. findViewById(R.id.rv_post_list);
        rvPostList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));


        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setdata();
    }

    private void setdata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Post> plist = AppDatabase.getDatabase(getContext()).postDao().getAllPostsDongtai();
                postDataList = new ArrayList<>();
                postDataList.add(new Post(1, "99", "这是第一条动态！", List.of("https://wx4.sinaimg.cn/mw690/005WUtI3ly1hpzad40xeaj30zu1bsq5q.jpg"), 2, 7,false));
                postDataList.addAll(plist);
                Log.e("=======",postDataList.toString());


                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new PostAdapter(getContext(), postDataList);
                        rvPostList.setAdapter(adapter);
                    }
                });

            }
        }).start();
    }
}

